<template>
  <div class="hotel-management">
    <div class="page-header">
      <h2>酒店管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增酒店
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="酒店名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入酒店名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input
            v-model="searchForm.contact"
            placeholder="请输入联系人"
            clearable
          />
        </el-form-item>
        <el-form-item label="酒店类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择酒店类型"
            clearable
          >
            <el-option label="经济型" value="economic" />
            <el-option label="舒适型" value="comfort" />
            <el-option label="高档型" value="luxury" />
            <el-option label="豪华型" value="premium" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 酒店列表 -->
    <el-card class="list-card">
      <el-table
        :data="sortedHotelList"
        style="width: 100%"
        v-loading="loading"
        border
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无酒店数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有添加任何酒店</div>
              <div class="empty-subtext">添加酒店信息丰富平台内容</div>
              <el-button type="primary" @click="handleAdd" class="mt-4">添加第一家酒店</el-button>
            </el-empty>
          </div>
        </template>
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column
          prop="name"
          label="酒店名称"
          min-width="150"
          sortable="custom"
        >
          <template #default="scope">
            <div class="hotel-info">
              <el-avatar :size="40" :src="scope.row.images[0].url" />
              <span class="hotel-name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="酒店类型"
          width="100"
          sortable="custom"
        >
          <template #default="scope">
            <el-tag :type="getHotelTypeTag(scope.row.type)">
              {{ getHotelTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column
          prop="address"
          label="地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="rating"
          label="评分"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100"
          sortable="custom"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="入驻时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="showDetail(scope.row)"
              >
                <el-icon><View /></el-icon> 详情
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleAudit(scope.row)"
                v-if="scope.row.status === 'pending'"
              >
                <el-icon><Check /></el-icon> 审核
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.id)"
              >
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 酒店详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="酒店详情"
      width="800px"
      :append-to-body="true"
      :modal-class="'hotel-detail-modal'"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <div class="hotel-detail">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h4 class="section-title">基本信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="酒店名称">{{
                currentHotel.name
              }}</el-descriptions-item>
              <el-descriptions-item label="酒店类型">
                <el-tag :type="getHotelTypeTag(currentHotel.type)">
                  {{ getHotelTypeLabel(currentHotel.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="联系人">{{
                currentHotel.contact
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                currentHotel.phone
              }}</el-descriptions-item>
              <el-descriptions-item label="酒店地址" :span="2">{{
                currentHotel.address
              }}</el-descriptions-item>
              <el-descriptions-item label="入驻时间">{{
                currentHotel.createTime
              }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(currentHotel.status)">
                  {{ getStatusLabel(currentHotel.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 酒店资质 -->
          <div class="detail-section">
            <h4 class="section-title">酒店资质</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="营业执照">
                <el-image
                  :src="currentHotel.license"
                  style="width: 100px; height: 100px"
                  :preview-src-list="[currentHotel.license]"
                />
              </el-descriptions-item>
              <el-descriptions-item label="法人代表">{{
                currentHotel.legalPerson
              }}</el-descriptions-item>
              <el-descriptions-item label="其他资质" :span="2">
                <div class="qualification-list">
                  <div
                    v-for="qual in currentHotel.qualifications"
                    :key="qual.name"
                    class="qual-item"
                  >
                    <el-image
                      :src="qual.url"
                      style="width: 80px; height: 80px"
                      :preview-src-list="[qual.url]"
                    />
                    <span class="qual-name">{{ qual.name }}</span>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 经营信息 -->
          <div class="detail-section">
            <h4 class="section-title">经营信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="营业时间"
                >{{ currentHotel.businessHours?.[0] }} -
                {{ currentHotel.businessHours?.[1] }}</el-descriptions-item
              >
              <el-descriptions-item label="房型数量"
                >{{ currentHotel.roomTypes }} 种</el-descriptions-item
              >
              <el-descriptions-item label="酒店标签">
                <el-tag
                  v-for="tag in currentHotel.tags"
                  :key="tag"
                  class="mx-1"
                >
                  {{ tag }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="设施服务">
                <el-tag
                  v-for="facility in currentHotel.facilities"
                  :key="facility"
                  class="mx-1"
                >
                  {{ facility }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="酒店介绍" :span="2">{{
                currentHotel.description
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 结算信息 -->
          <div class="detail-section">
            <h4 class="section-title">结算信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="开户银行">{{
                currentHotel.bankName
              }}</el-descriptions-item>
              <el-descriptions-item label="银行账号">{{
                currentHotel.bankAccount
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="酒店审核"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditFormRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="拒绝原因"
          prop="reason"
          v-if="auditForm.status === 'rejected'"
        >
          <el-input
            v-model="auditForm.reason"
            type="textarea"
            rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAudit"
            :disabled="isSubmitDisabled"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="dialogType === 'add' ? '新增酒店' : '编辑酒店'"
      width="800px"
      :append-to-body="true"
      :modal-class="'hotel-edit-modal'"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="120px"
          class="hotel-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h4 class="section-title">基本信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="酒店名称" prop="name">
                  <el-input
                    v-model="editForm.name"
                    placeholder="请输入酒店名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="酒店类型" prop="type">
                  <el-select
                    v-model="editForm.type"
                    placeholder="请选择酒店类型"
                    style="width: 100%"
                  >
                    <el-option label="经济型" value="economic" />
                    <el-option label="舒适型" value="comfort" />
                    <el-option label="高档型" value="luxury" />
                    <el-option label="豪华型" value="premium" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contact">
                  <el-input
                    v-model="editForm.contact"
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="editForm.phone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="酒店地址" prop="address">
              <el-input
                v-model="editForm.address"
                placeholder="请输入酒店地址"
              />
            </el-form-item>

            <el-form-item label="酒店介绍" prop="description">
              <el-input
                type="textarea"
                v-model="editForm.description"
                :rows="3"
                placeholder="请输入酒店介绍"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="酒店Logo" prop="logo">
                  <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleLogoSuccess"
                    :before-upload="beforeLogoUpload"
                  >
                    <img
                      v-if="editForm.logo"
                      :src="editForm.logo"
                      class="avatar"
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 酒店资质 -->
          <div class="form-section">
            <h4 class="section-title">酒店资质</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="法人代表" prop="legalPerson">
                  <el-input
                    v-model="editForm.legalPerson"
                    placeholder="请输入法人代表姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input
                    v-model="editForm.idCard"
                    placeholder="请输入法人身份证号"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="营业执照" prop="license">
              <el-upload
                class="license-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeLicenseUpload"
              >
                <img
                  v-if="editForm.license"
                  :src="editForm.license"
                  class="license"
                />
                <el-icon v-else class="license-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="其他资质" prop="qualifications">
              <el-upload
                class="qualification-uploader"
                action="/api/upload"
                :file-list="editForm.qualifications"
                :on-success="handleQualificationSuccess"
                :on-remove="handleQualificationRemove"
                list-type="picture-card"
                multiple
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 经营信息 -->
          <div class="form-section">
            <h4 class="section-title">经营信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="营业时间" prop="businessHours">
                  <div class="time-picker-group">
                    <el-time-picker
                      v-model="editForm.businessHours[0]"
                      placeholder="开始时间"
                      format="HH:mm"
                      value-format="HH:mm"
                    />
                    <span class="time-separator">至</span>
                    <el-time-picker
                      v-model="editForm.businessHours[1]"
                      placeholder="结束时间"
                      format="HH:mm"
                      value-format="HH:mm"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房型数量" prop="roomTypes">
                  <el-input-number
                    v-model="editForm.roomTypes"
                    :min="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="酒店标签" prop="tags">
              <el-select
                v-model="editForm.tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in tagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="设施服务" prop="facilities">
              <el-select
                v-model="editForm.facilities"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入设施服务"
                style="width: 100%"
              >
                <el-option
                  v-for="facility in facilityOptions"
                  :key="facility"
                  :label="facility"
                  :value="facility"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="酒店图片" prop="images">
              <el-upload
                class="image-uploader"
                action="/api/upload"
                :file-list="editForm.images"
                :on-success="handleImageSuccess"
                :on-remove="handleImageRemove"
                list-type="picture-card"
                multiple
                :before-upload="beforeImageUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 结算信息 -->
          <div class="form-section">
            <h4 class="section-title">结算信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName">
                  <el-input
                    v-model="editForm.bankName"
                    placeholder="请输入开户银行"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankAccount">
                  <el-input
                    v-model="editForm.bankAccount"
                    placeholder="请输入银行账号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Refresh,
  Edit,
  View,
  Delete,
  Check,
  Picture,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  contact: "",
  type: "",
  status: "",
});

// 列表数据
const loading = ref(false);
const hotelList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 详情相关
const detailVisible = ref(false);
const currentHotel = ref({});

// 审核相关
const auditDialogVisible = ref(false);
const auditFormRef = ref(null);
const auditForm = reactive({
  status: "approved",
  reason: "",
});

// 审核表单验证规则
const auditFormRules = {
  status: [{ required: true, message: "请选择审核结果", trigger: "change" }],
  reason: [{ required: true, message: "请输入拒绝原因", trigger: "blur" }],
};

// 编辑相关
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const dialogType = ref("add");
const editForm = reactive({
  id: "",
  name: "",
  type: "",
  contact: "",
  phone: "",
  address: "",
  description: "",
  logo: "",
  businessHours: ["08:00", "22:00"],
  roomTypes: 1,
  tags: [],
  facilities: [],
  bankName: "",
  bankAccount: "",
  // 新增字段
  legalPerson: "",
  idCard: "",
  license: "",
  qualifications: [],
  images: [],
});

// 表单校验规则
const editFormRules = {
  name: [{ required: true, message: "请输入酒店名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择酒店类型", trigger: "change" }],
  contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入酒店地址", trigger: "blur" }],
  bankName: [{ required: true, message: "请输入开户银行", trigger: "blur" }],
  bankAccount: [{ required: true, message: "请输入银行账号", trigger: "blur" }],
  // 新增验证规则
  legalPerson: [{ required: true, message: "请输入法人代表", trigger: "blur" }],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  license: [{ required: true, message: "请上传营业执照", trigger: "change" }],
};

// 标签和设施选项
const tagOptions = ["商务酒店", "会议服务", "餐饮", "休闲度假", "亲子酒店"];
const facilityOptions = [
  "停车场",
  "游泳池",
  "健身房",
  "会议室",
  "WiFi",
  "餐厅",
];

// 计算属性：排序后的列表
const sortedHotelList = computed(() => {
  let sortedList = [...hotelList.value];

  // 根据搜索条件过滤
  sortedList = sortedList.filter((hotel) => {
    const nameMatch =
      !searchForm.name ||
      hotel.name.toLowerCase().includes(searchForm.name.toLowerCase());
    const contactMatch =
      !searchForm.contact ||
      hotel.contact.toLowerCase().includes(searchForm.contact.toLowerCase());
    const typeMatch = !searchForm.type || hotel.type === searchForm.type;
    const statusMatch =
      !searchForm.status || hotel.status === searchForm.status;
    return nameMatch && contactMatch && typeMatch && statusMatch;
  });

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return sortedList.slice(start, end);
});

// 酒店类型标签
const getHotelTypeTag = (type) => {
  const typeMap = {
    economic: "info",
    comfort: "",
    luxury: "success",
    premium: "warning",
  };
  return typeMap[type] || "info";
};

const getHotelTypeLabel = (type) => {
  const typeMap = {
    economic: "经济型",
    comfort: "舒适型",
    luxury: "高档型",
    premium: "豪华型",
  };
  return typeMap[type] || "未知";
};

// 状态标签
const getStatusType = (status) => {
  const statusMap = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
  };
  return statusMap[status] || "info";
};

const getStatusLabel = (status) => {
  const statusMap = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已拒绝",
  };
  return statusMap[status] || "未知";
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 排序处理
const handleSortChange = ({ prop, order }) => {
  // TODO: 实现排序逻辑
  fetchData();
};

// 新增酒店
const handleAdd = () => {
  dialogType.value = "add";
  Object.keys(editForm).forEach((key) => {
    if (key === "businessHours") {
      editForm[key] = ["08:00", "22:00"];
    } else if (key === "roomTypes") {
      editForm[key] = 1;
    } else if (Array.isArray(editForm[key])) {
      editForm[key] = [];
    } else {
      editForm[key] = "";
    }
  });
  editDialogVisible.value = true;
};

// 显示详情
const showDetail = (row) => {
  currentHotel.value = { ...row };
  detailVisible.value = true;
};

// 编辑酒店
const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    type: row.type,
    contact: row.contact,
    phone: row.phone,
    address: row.address,
    description: row.description,
    logo: row.logo,
    businessHours: row.businessHours || ["08:00", "22:00"],
    roomTypes: row.roomTypes || 1,
    tags: row.tags || [],
    facilities: row.facilities || [],
    bankName: row.bankName,
    bankAccount: row.bankAccount,
    // 新增字段
    legalPerson: row.legalPerson,
    idCard: row.idCard,
    license: row.license,
    qualifications: row.qualifications || [],
    images: row.images || [],
  });
  if (detailVisible.value) {
    detailVisible.value = false;
  }
  editDialogVisible.value = true;
};

// 删除酒店
const handleDelete = async (id) => {
  const confirmResult = await ElMessageBox.confirm(
    "确定要删除该酒店吗？",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch((err) => err);

  if (confirmResult !== "confirm") {
    return;
  }

  try {
    const result = await axios.delete(`/admin/hotels/${id}`);
    
    if (result.code === 200) {
      ElMessage.success("删除成功");
      fetchData();
    } else {
      ElMessage.error(result.message || "删除失败");
    }
  } catch (error) {
    console.error("删除酒店失败：", error);
    ElMessage.error("删除酒店失败");
  }
};

// 打开审核对话框
const handleAudit = (row) => {
  currentHotel.value = JSON.parse(JSON.stringify(row));
  auditForm.status = row.status;
  auditForm.reason = row.rejectReason || '';
  auditDialogVisible.value = true;
};

// 提交审核
const submitAudit = async () => {
  auditFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      const params = {
        status: auditForm.status,
        rejectReason: auditForm.status === 'rejected' ? auditForm.reason : '',
      };

      const result = await axios.put(`/admin/hotels/${currentHotel.value.id}/audit`, params);
      
      if (result.code === 200) {
        ElMessage.success("审核操作成功");
        auditDialogVisible.value = false;
        fetchData();
      } else {
        ElMessage.error(result.message || "审核操作失败");
      }
    } catch (error) {
      console.error("审核操作失败：", error);
      ElMessage.error("审核操作失败");
    }
  });
};

// 提交编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    if (dialogType.value === "add") {
      // 新增酒店
      const newHotel = {
        ...editForm,
        id: hotelList.value.length + 1,
        status: "pending",
        createTime: new Date().toLocaleString(),
        rating: 5.0,
      };
      hotelList.value.push(newHotel);
      ElMessage.success("添加成功");
    } else {
      // 更新酒店
      const index = hotelList.value.findIndex(
        (item) => item.id === editForm.id,
      );
      if (index !== -1) {
        hotelList.value[index] = {
          ...hotelList.value[index],
          ...editForm,
        };
        ElMessage.success("更新成功");
      }
    }

    editDialogVisible.value = false;
    fetchData();
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// Logo上传
const handleLogoSuccess = (res) => {
  editForm.logo = res.data.url;
};

const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传头像图片只能是图片格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 文件上传处理函数
const handleLicenseSuccess = (res) => {
  editForm.license = res.data.url;
};

const beforeLicenseUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("上传营业执照只能是图片格式!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("上传营业执照大小不能超过 5MB!");
    return false;
  }
  return true;
};

const handleQualificationSuccess = (res, file) => {
  editForm.qualifications.push({
    name: file.name,
    url: res.data.url,
  });
};

const handleQualificationRemove = (file) => {
  const index = editForm.qualifications.findIndex(
    (item) => item.url === file.url,
  );
  if (index !== -1) {
    editForm.qualifications.splice(index, 1);
  }
};

const handleImageSuccess = (res, file) => {
  editForm.images.push({
    name: file.name,
    url: res.data.url,
  });
};

const handleImageRemove = (file) => {
  const index = editForm.images.findIndex((item) => item.url === file.url);
  if (index !== -1) {
    editForm.images.splice(index, 1);
  }
};

// 添加图片上传前的验证函数
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchForm.name || undefined,
      contact: searchForm.contact || undefined,
      type: searchForm.type || undefined,
      status: searchForm.status || undefined,
    };

    const result = await axios.get("/admin/hotels", { params });
    
    if (result.code === 200 && result.data) {
      // 对API返回的数据进行字段映射
      hotelList.value = (result.data.records || []).map(item => ({
        id: item.id,
        name: item.name,
        type: item.type || "comfort", // 使用默认类型
        contact: item.contactName,
        phone: item.contactPhone,
        address: item.address,
        description: item.description,
        logo: item.avatar || item.coverUrl,
        businessHours: [item.checkInTime || "14:00", item.checkOutTime || "12:00"],
        roomTypes: 3, // 默认值
        tags: item.tags ? item.tags.split(',') : [],
        facilities: ["WiFi", "停车场"], // 默认设施
        status: item.status,
        createTime: item.createTime,
        rating: item.rating || 4.0,
        bankName: "暂无", // 默认值
        bankAccount: "暂无", // 默认值
        legalPerson: item.contactName,
        idCard: "",
        license: item.businessLicense,
        qualifications: [],
        // 添加图片数组
        images: [
          { name: "封面图", url: item.coverUrl || "https://via.placeholder.com/800x600" }
        ]
      }));
      total.value = result.data.total || 0;
    } else {
      // 使用测试数据
      useFilteredMockData();
    }
  } catch (error) {
    console.error("获取酒店列表失败：", error);
    ElMessage.error("获取酒店列表失败，使用测试数据");
    
    // 使用测试数据
    useFilteredMockData();
  } finally {
    loading.value = false;
  }
};

// 使用过滤后的测试数据
const useFilteredMockData = () => {
  // 测试数据
  const mockData = [
    {
      id: 1,
      name: "桂江大酒店",
      type: "luxury",
      contact: "李经理",
      phone: "13800138001",
      address: "桂林市七星区桂江路123号",
      description: "位于桂江旁的豪华酒店，环境优美，服务一流。",
      logo: "https://via.placeholder.com/150",
      businessHours: ["07:00", "23:00"],
      roomTypes: 5,
      tags: ["商务酒店", "会议服务", "餐饮"],
      facilities: ["停车场", "游泳池", "健身房", "会议室", "WiFi", "餐厅"],
      status: "approved",
      createTime: "2023-05-10 13:24:56",
      rating: 4.8,
      bankName: "中国银行",
      bankAccount: "6225760087654321",
      legalPerson: "李大明",
      idCard: "450123198801011234",
      license: "https://via.placeholder.com/300x400",
      qualifications: [
        { name: "卫生许可证", url: "https://via.placeholder.com/300x400" },
        { name: "消防证", url: "https://via.placeholder.com/300x400" },
      ],
      images: [
        { name: "外观", url: "https://via.placeholder.com/800x600" },
        { name: "大堂", url: "https://via.placeholder.com/800x600" },
        { name: "客房", url: "https://via.placeholder.com/800x600" },
      ],
    },
    {
      id: 2,
      name: "漓江假日酒店",
      type: "comfort",
      contact: "张经理",
      phone: "13900139001",
      address: "桂林市象山区漓江路456号",
      description: "漓江边舒适型酒店，享受漓江美景。",
      logo: "https://via.placeholder.com/150",
      businessHours: ["08:00", "22:00"],
      roomTypes: 3,
      tags: ["休闲度假", "商务酒店"],
      facilities: ["停车场", "WiFi", "餐厅"],
      status: "pending",
      createTime: "2023-06-15 09:15:30",
      rating: 4.2,
      bankName: "农业银行",
      bankAccount: "6228481234567890",
      legalPerson: "张小红",
      idCard: "450123199001015678",
      license: "https://via.placeholder.com/300x400",
      qualifications: [
        { name: "卫生许可证", url: "https://via.placeholder.com/300x400" },
      ],
      images: [
        { name: "外观", url: "https://via.placeholder.com/800x600" },
        { name: "客房", url: "https://via.placeholder.com/800x600" },
      ],
    },
    {
      id: 3,
      name: "桂湖度假酒店",
      type: "premium",
      contact: "王总",
      phone: "13700137001",
      address: "桂林市七星区桂湖公园旁",
      description: "桂湖畔的豪华度假酒店，拥有超大泳池和spa。",
      logo: "https://via.placeholder.com/150",
      businessHours: ["00:00", "24:00"],
      roomTypes: 7,
      tags: ["休闲度假", "亲子酒店"],
      facilities: ["停车场", "游泳池", "健身房", "餐厅", "儿童乐园"],
      status: "approved",
      createTime: "2023-04-20 14:35:12",
      rating: 4.9,
      bankName: "建设银行",
      bankAccount: "6227001234567890",
      legalPerson: "王大力",
      idCard: "450123197701019876",
      license: "https://via.placeholder.com/300x400",
      qualifications: [
        { name: "卫生许可证", url: "https://via.placeholder.com/300x400" },
        { name: "消防证", url: "https://via.placeholder.com/300x400" },
        { name: "游泳池安全证", url: "https://via.placeholder.com/300x400" },
      ],
      images: [
        { name: "外观", url: "https://via.placeholder.com/800x600" },
        { name: "大堂", url: "https://via.placeholder.com/800x600" },
        { name: "泳池", url: "https://via.placeholder.com/800x600" },
        { name: "客房", url: "https://via.placeholder.com/800x600" },
      ],
    },
    {
      id: 4,
      name: "象山快捷酒店",
      type: "economic",
      contact: "赵经理",
      phone: "13600136001",
      address: "桂林市象山区象山路789号",
      description: "经济实惠的快捷酒店，交通便利。",
      logo: "https://via.placeholder.com/150",
      businessHours: ["14:00", "12:00"],
      roomTypes: 2,
      tags: ["经济型"],
      facilities: ["WiFi"],
      status: "rejected",
      createTime: "2023-07-05 10:22:45",
      rating: 3.5,
      bankName: "工商银行",
      bankAccount: "6212261234567890",
      legalPerson: "赵小明",
      idCard: "450123198501014321",
      license: "https://via.placeholder.com/300x400",
      qualifications: [
        { name: "卫生许可证", url: "https://via.placeholder.com/300x400" },
      ],
      images: [
        { name: "外观", url: "https://via.placeholder.com/800x600" },
        { name: "客房", url: "https://via.placeholder.com/800x600" },
      ],
      rejectReason: "消防设施不达标，需要整改后重新申请。",
    },
    {
      id: 5,
      name: "叠彩山庄酒店",
      type: "luxury",
      contact: "陈总",
      phone: "13500135001",
      address: "桂林市叠彩区叠彩路234号",
      description: "位于叠彩山旁的高档酒店，风景秀丽。",
      logo: "https://via.placeholder.com/150",
      businessHours: ["12:00", "12:00"],
      roomTypes: 4,
      tags: ["商务酒店", "休闲度假"],
      facilities: ["停车场", "会议室", "WiFi", "餐厅"],
      status: "approved",
      createTime: "2023-03-15 16:48:30",
      rating: 4.6,
      bankName: "招商银行",
      bankAccount: "6225881234567890",
      legalPerson: "陈小华",
      idCard: "450123198201017654",
      license: "https://via.placeholder.com/300x400",
      qualifications: [
        { name: "卫生许可证", url: "https://via.placeholder.com/300x400" },
        { name: "消防证", url: "https://via.placeholder.com/300x400" },
      ],
      images: [
        { name: "外观", url: "https://via.placeholder.com/800x600" },
        { name: "大堂", url: "https://via.placeholder.com/800x600" },
        { name: "客房", url: "https://via.placeholder.com/800x600" },
      ],
    },
  ];

  // 根据搜索条件筛选数据
  let filteredData = mockData.filter((item) => {
    let match = true;
    
    if (searchForm.name) {
      match = match && item.name.toLowerCase().includes(searchForm.name.toLowerCase());
    }
    
    if (searchForm.contact) {
      match = match && item.contact.toLowerCase().includes(searchForm.contact.toLowerCase());
    }
    
    if (searchForm.type) {
      match = match && item.type === searchForm.type;
    }
    
    if (searchForm.status) {
      match = match && item.status === searchForm.status;
    }
    
    return match;
  });

  // 总记录数
  total.value = filteredData.length;
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  hotelList.value = filteredData.slice(start, end);
};

// 导出Excel
const exportToExcel = () => {
  // 指定导出的列
  const header = {
    id: 'ID',
    name: '酒店名称',
    type: '酒店类型',
    contact: '联系人',
    phone: '联系电话',
    address: '酒店地址',
    rating: '评分',
    status: '状态'
  };
  
  // 转换状态值
  const data = hotelList.value.map(item => {
    const newItem = { ...item };
    // 转换酒店类型显示
    if (newItem.type === 'luxury') {
      newItem.type = '豪华型';
    } else if (newItem.type === 'premium') {
      newItem.type = '高档型';
    } else if (newItem.type === 'comfort') {
      newItem.type = '舒适型';
    } else if (newItem.type === 'economic') {
      newItem.type = '经济型';
    }
    
    // 转换状态显示
    if (newItem.status === 'pending') {
      newItem.status = '待审核';
    } else if (newItem.status === 'approved') {
      newItem.status = '已通过';
    } else if (newItem.status === 'rejected') {
      newItem.status = '已拒绝';
    }
    
    return newItem;
  });
  
  // 导出Excel
  const worksheet = XLSX.utils.json_to_sheet(data, { header: Object.keys(header) });
  
  // 设置表头
  XLSX.utils.sheet_add_aoa(worksheet, [Object.values(header)], { origin: 'A1' });
  
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '酒店列表');
  
  // 保存Excel文件
  XLSX.writeFile(workbook, `酒店列表_${new Date().toLocaleDateString()}.xlsx`);
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.hotel-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .list-card {
    margin-bottom: 20px;
  }

  .hotel-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .hotel-name {
      font-weight: bold;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  /* 编辑模态框样式 */
  :deep(.hotel-edit-modal) {
    .el-dialog {
      margin: 0 auto;
      position: relative;
      max-height: 90vh;
      display: flex;
      flex-direction: column;
      width: min(90%, 800px);
    }

    .el-dialog__body {
      flex: 1;
      overflow: hidden;
      padding: 0;
    }

    .el-scrollbar {
      &__view {
        padding: 20px;
      }
    }

    .el-dialog__header {
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__footer {
      margin: 0;
      padding: 20px;
      border-top: 1px solid var(--el-border-color-light);
    }
  }

  .hotel-form {
    padding: 20px;
  }

  .form-section {
    margin-bottom: clamp(20px, 3vh, 30px);
    padding-bottom: clamp(15px, 2vh, 20px);
    border-bottom: 1px solid var(--el-border-color-light);

    &:last-child {
      margin-bottom: 0;
      padding-bottom: 0;
      border-bottom: none;
    }
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 20px;
    color: var(--el-text-color-primary);
    padding-left: 10px;
    border-left: 3px solid var(--el-color-primary);
  }

  .time-picker-group {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;

    .el-time-picker {
      flex: 1;
    }

    .time-separator {
      color: var(--el-text-color-regular);
    }
  }

  .avatar-uploader {
    display: flex;
    justify-content: center;

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .avatar-uploader-icon {
      width: 178px;
      height: 178px;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      color: #8c939d;
    }
  }

  .license-uploader,
  .qualification-uploader,
  .image-uploader {
    :deep(.el-upload) {
      width: 178px;
      height: 178px;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .license {
      width: 178px;
      height: 178px;
      display: block;
    }

    .license-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .qualification-uploader,
  .image-uploader {
    :deep(.el-upload-list) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    :deep(.el-upload-list__item) {
      width: 178px;
      height: 178px;
      margin: 0;
    }
  }

  /* 响应式布局 */
  @media (max-width: 768px) {
    padding: 12px;

    .search-form {
      padding: 16px;
    }

    .avatar-uploader {
      .avatar,
      .avatar-uploader-icon {
        width: 120px;
        height: 120px;
      }
    }
  }
}
</style>
